<template>
    <div class="loginMain">
        <div class="userInput">
            <label>精准扶贫后台登录</label>
            <el-form :model="formLabelAlign" ref="formLabelAlign" label-width="100px" :rules="rule">
                <el-form-item label="账号" style="text-align:left" prop="logincode">
                    <el-input v-model="formLabelAlign.logincode" style="width:250px;"></el-input>
                </el-form-item>
                <el-form-item label="密码" style="text-align:left" prop="password">
                    <el-input v-model="formLabelAlign.password" type="password" style="width:250px;"></el-input>
                </el-form-item>
                <el-form-item label="角色" v-if="!toLogin">
                    <el-row>
                        <el-col :span="7" align="left" v-for="(item,index) in roles" :key="item.id">
                            <el-button size="mini" style="width: 75px" @click="chooseRole(index)"
                                       :class="chosenRoleIndex==index?'chosen':'unchosen'">
                                {{item.name}}
                            </el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item :label="chosenRole.name+'名称'" style="text-align:left"
                              v-if="chosenRoleIndex!=-1&&!toLogin&&chosenRole.needOrg">
                    <el-input v-model="formLabelAlign.orgName" style="width:250px;"></el-input>
                </el-form-item>

            </el-form>
            <div align="center">
                <el-button type="primary" @click="login('ruleForm')" size="medium" v-if="toLogin"
                           style="margin-right: 50px">登录
                </el-button>
                <el-button type="primary" @click="registerAccount('ruleForm')" size="medium" v-if="!toLogin"
                           style="margin-right: 50px">注册
                </el-button>
                <el-button type="text" @click="toLogin=!toLogin" size="medium">
                    {{toLogin?'没有账号，去注册':'已有账号，去登录'}}
                </el-button>
            </div>
        </div>

    </div>
</template>

<script>
    import {searchRoleList, registerAccount, userLogin} from "@/api/roleApi";
    import {setCookie} from "@/utils/auth";
    import axios from "axios";
    import eventBus from "@/utils/eventBus";

    export default {
        data() {
            var logincodeValid = (rule, value, callback) => {
                if (this.toLogin) {
                    callback()
                }
                let reg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
                if (!(reg.test(value))) {
                    callback(new Error("身份证号格式错误"))
                } else {
                    callback()
                }
            }
            return {
                chosenRoleIndex: -1,
                radio: 3,
                toLogin: true,//？登录：注册
                labelPosition: 'right',
                chosenRole: {},
                formLabelAlign: {
                    logincode: null,
                    password: null,
                    roleId: null,
                    needOrg: null, //是否需要创建机构
                    orgName: null
                },
                rule: {
                    logincode: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                        {validator: logincodeValid, trigger: 'blur'}],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 5, max: 12, message: '长度在 5 到 12个字符'},
                        {pattern: /^(\w){5,12}$/, message: '只能输入5-25个字母、数字、下划线'}
                    ]
                },
                roles: []
            };
        },
        created() {
            this.searchRoleList();
        },
        methods: {
            //查询角色列表
            searchRoleList() {
                searchRoleList().then(res => {
                    this.roles = res;
                }, err => {
                })
            },
            //选择角色
            chooseRole(index) {
                this.chosenRoleIndex = index;
                this.chosenRole = this.roles[index];
                this.formLabelAlign.roleId = this.roles[index].id;
                this.formLabelAlign.needOrg = this.roles[index].needOrg;
            },
            //登录
            login() {
                userLogin(this.formLabelAlign).then(res => {
                    this.$message.success('登录成功')
                    setCookie('ACCESSTOKEN', res.ACCESSTOKEN)
                    axios.defaults.headers.common["ACCESSTOKEN"] = res.ACCESSTOKEN;//将token放到请求头里
                    eventBus.$emit('search_userMenu', true);
                    this.$router.push({path: '/'})
                })
            },
            //注册
            registerAccount() {
                this.$refs['formLabelAlign'].validate((valid) => {
                    if (valid) {
                        if (this.chosenRoleIndex == -1) {
                            this.$message.error("请选择角色");
                            return;
                        }
                        registerAccount(this.formLabelAlign).then(res => {
                            this.toLogin = true;
                            this.$message.success("账号注册成功");
                        });

                    } else {
                        this.$message.warning("请输入正确的信息");
                    }
                });

            },

            submitForm(formName) {
                this.$router.push({
                    path: '/index'
                })
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        }
    }
</script>

<style lang="scss" scoped>
    .loginMain {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: url("../assets/bg.png") no-repeat 100%;
        background-size: cover;

        .userInput {
            width: 400px;
            min-height: 300px;
            background: rgba(255, 255, 255, .8);
            border-radius: 6px;
            padding: 10px;
            position: absolute;
            right: 10%;
            top: 30%;

            label {
                display: block;
                height: 40px;
                line-height: 40px;
                text-align: center;
                margin: 15px auto;
                font-size: 24px;
            }
        }

        .unchosen {
            padding: 8px;
        }

        .chosen {
            background-color: #3997ee;
            color: white;
            padding: 8px;
        }
    }
</style>